"""
把VOC格式的数据集转换成COCO格式的数据集

运行前先自查:
1. 算法的数据集是否需要背景类别
2. coco格式dataset不需要(不能)加上背景编号,需要从1开始编号而不是0'

输入VOC格式数据集样例:
.
`-- VOC2007
    |-- Annotations
    |   |-- 499.xml
    |   `-- 500.xml
    `-- JPEGImages
        |-- 499.jpg
        `-- 500.jpg

输出COCO格式的数据集样例:
.
`-- cocodataset
    |-- annotations
    |   |-- instances_train2017.json
    |   `-- instances_val2017.json
    |-- train2017
    |   |-- 2998.jpg
    |   `-- 2999.jpg
    `-- val2017
        |-- 2997.jpg
        `-- 3000.jpg
"""
import glob
import random
import shutil
import xml.etree.ElementTree as ET
import os
import json
from collections import OrderedDict
import argparse


# 定义默认参数
parser = argparse.ArgumentParser()
parser.add_argument("--coco_root", type=str,
                    default="./cocodataset",
                    help="root to save coco datasets")

parser.add_argument("--train_voc_xml_dir", type=str,
                    default="/ai_home/dataset/public_train_data/1/label",
                    help="annotation dir of train voc dataset")
parser.add_argument("--train_voc_jpg_dir", type=str,
                    default="/ai_home/dataset/public_train_data/1/src",
                    help="image dir of train voc dataset")

parser.add_argument("--test_voc_xml_dir", type=str,
                    default="/ai_home/dataset/test_data/1/label",
                    help="annotation dir of test voc dataset")
parser.add_argument("--test_voc_jpg_dir", type=str,
                    default="/ai_home/dataset/test_data/1/src",
                    help="image dir of test voc dataset")
opt = parser.parse_args()


# 定义类别名与编号的映射关系
category_set = OrderedDict({
    "03040001": 1,
    "03010001": 2,
    "02020001": 3,
    "02010001": 4,
    "03020001": 5,
    "03030001": 6})

image_set = set()
image_id = 20180000000
annotation_id = 0


def addCatItem(name, coco_json):
    category_item_id = category_set[name]
    category_item = dict()
    category_item['supercategory'] = 'none'
    category_item['id'] = category_item_id
    category_item['name'] = name
    coco_json['categories'].append(category_item)
    return category_item_id


def addImgItem(file_name, size, coco_json):
    global image_id
    if file_name is None:
        raise Exception('Could not find filename tag in xml file.')
    if size['width'] is None:
        raise Exception('Could not find width tag in xml file.')
    if size['height'] is None:
        raise Exception('Could not find height tag in xml file.')
    image_id += 1
    image_item = dict()
    image_item['id'] = image_id
    image_item['file_name'] = file_name
    image_item['width'] = size['width']
    image_item['height'] = size['height']
    coco_json['images'].append(image_item)
    image_set.add(file_name)
    return image_id


def addAnnoItem(object_name, image_id, category_id, bbox, coco_json):
    global annotation_id
    annotation_item = dict()
    annotation_item['segmentation'] = []
    seg = []
    # bbox[] is x,y,w,h
    # left_top
    seg.append(bbox[0])
    seg.append(bbox[1])
    # left_bottom
    seg.append(bbox[0])
    seg.append(bbox[1] + bbox[3])
    # right_bottom
    seg.append(bbox[0] + bbox[2])
    seg.append(bbox[1] + bbox[3])
    # right_top
    seg.append(bbox[0] + bbox[2])
    seg.append(bbox[1])

    annotation_item['segmentation'].append(seg)

    annotation_item['area'] = bbox[2] * bbox[3]
    annotation_item['iscrowd'] = 0
    annotation_item['ignore'] = 0
    annotation_item['image_id'] = image_id
    annotation_item['bbox'] = bbox
    annotation_item['category_id'] = category_id
    annotation_id += 1
    annotation_item['id'] = annotation_id
    coco_json['annotations'].append(annotation_item)


def _read_image_ids(image_sets_file):
    ids = []
    with open(image_sets_file) as f:
        for line in f:
            ids.append(line.rstrip())
    return ids


def parseXmlFiles(xml_list, json_save_path, coco_json):
    for xml_file in xml_list:
        if not xml_file.endswith('.xml'):
            continue

        bndbox = dict()
        size = dict()
        current_image_id = None
        current_category_id = None
        file_name = None
        size['width'] = None
        size['height'] = None
        size['depth'] = None

        tree = ET.parse(xml_file)
        root = tree.getroot()
        if root.tag != 'annotation':
            raise Exception('pascal voc xml root element should be annotation, rather than {}'.format(root.tag))

        # elem is <folder>, <filename>, <size>, <object>
        for elem in root:
            current_parent = elem.tag
            current_sub = None
            object_name = None

            if elem.tag == 'folder':
                continue

            if elem.tag == 'filename':
                file_name = elem.text
                if file_name in category_set:
                    raise Exception('file_name duplicated')

            # add img item only after parse <size> tag
            elif current_image_id is None and file_name is not None and size['width'] is not None:
                if file_name not in image_set:
                    current_image_id = addImgItem(file_name, size, coco_json)
                    print('add image with {} and {}'.format(file_name, size))
                else:
                    # print('duplicated image: {}, skipped'.format(file_name))
                    # continue
                    raise Exception('duplicated image: {}'.format(file_name))
                    # subelem is <width>, <height>, <depth>, <name>, <bndbox>
            for subelem in elem:
                bndbox['xmin'] = None
                bndbox['xmax'] = None
                bndbox['ymin'] = None
                bndbox['ymax'] = None

                current_sub = subelem.tag
                if current_parent == 'object' and subelem.tag == 'name':
                    object_name = subelem.text
                    current_category_id = category_set[object_name]

                elif current_parent == 'size':
                    if size[subelem.tag] is not None:
                        raise Exception('xml structure broken at size tag.')
                    size[subelem.tag] = int(subelem.text)

                # option is <xmin>, <ymin>, <xmax>, <ymax>, when subelem is <bndbox>
                for option in subelem:
                    if current_sub == 'bndbox':
                        if bndbox[option.tag] is not None:
                            raise Exception('xml structure corrupted at bndbox tag.')
                        bndbox[option.tag] = int(option.text)

                # only after parse the <object> tag
                if bndbox['xmin'] is not None:
                    if object_name is None:
                        raise Exception('xml structure broken at bndbox tag')
                    if current_image_id is None:
                        raise Exception('xml structure broken at bndbox tag')
                    if current_category_id is None:
                        raise Exception('xml structure broken at bndbox tag')
                    bbox = []
                    # x
                    bbox.append(bndbox['xmin'])
                    # y
                    bbox.append(bndbox['ymin'])
                    # w
                    bbox.append(bndbox['xmax'] - bndbox['xmin'])
                    # h
                    bbox.append(bndbox['ymax'] - bndbox['ymin'])
                    print('add annotation with {},{},{},{}'.format(object_name, current_image_id, current_category_id,
                                                                   bbox))
                    addAnnoItem(object_name, current_image_id, current_category_id, bbox, coco_json)
    json.dump(coco_json, open(json_save_path, 'w'))


def init_json_file():
    coco_json = dict()
    coco_json['images'] = []
    coco_json['type'] = 'instances'
    coco_json['annotations'] = []
    coco_json['categories'] = []
    # create coco category
    for category_name in category_set:
        addCatItem(category_name, coco_json=coco_json)
    return coco_json


def main():
    # 创建coco目录,如果之前已经存在了,就删除
    coco_anno_path = os.path.join(opt.coco_root, "annotations")
    coco_train_path = os.path.join(opt.coco_root, "train2017")
    coco_test_path = os.path.join(opt.coco_root, "val2017")

    if os.path.exists(opt.coco_root):
        shutil.rmtree(opt.coco_root)

    os.makedirs(coco_anno_path)
    os.makedirs(coco_train_path)
    os.makedirs(coco_test_path)

    # 遍历训练集目录
    train_xml_path_regex = opt.train_voc_xml_dir + "/*.xml"  # 这是xml文件所在的地址
    train_xml_list = glob.glob(train_xml_path_regex)
    random.shuffle(train_xml_list)
    # 遍历测试集目录
    test_xml_path_regex = opt.test_voc_xml_dir + "/*.xml"  # 这是xml文件所在的地址
    test_xml_list = glob.glob(test_xml_path_regex)
    random.shuffle(test_xml_list)

    for file in train_xml_list:
        shutil.copy(os.path.join(opt.train_voc_jpg_dir, os.path.basename(file)[:-3]+"jpg"),
                    os.path.join(coco_train_path, os.path.basename(file)[:-3]+"jpg"))

    for file in test_xml_list:
        shutil.copy(os.path.join(opt.test_voc_jpg_dir, os.path.basename(file)[:-3] + "jpg"),
                    os.path.join(coco_test_path, os.path.basename(file)[:-3] + "jpg"))

    # 通过文件夹生成train
    train_coco_json = init_json_file()
    train_json_save_path = os.path.join(coco_anno_path, "instances_train2017.json")
    parseXmlFiles(train_xml_list, train_json_save_path, train_coco_json)
    # test
    test_coco_json = init_json_file()
    test_json_save_path = os.path.join(coco_anno_path, "instances_val2017.json")
    parseXmlFiles(test_xml_list, test_json_save_path, test_coco_json)


if __name__ == '__main__':
    main()
